<script setup>
  import { ref, watch } from 'vue'
  import { useForm } from 'vee-validate'

  import { getDefaults, buildYupSchema, getFieldData } from '@/helpers/form'
  import { useProjectConfigStore, useProjectStore } from '@/stores/project'
  import DebugContent from '@/components/DebugContent.vue'
  import Input from '@/components/forms/Input.vue'
  import RadioChoice from '@/components/forms/RadioChoice.vue'
  import CheckboxList from '@/components/forms/CheckboxList.vue'
  import {
    getSubmitErrorCallback,
    getSubmitModelCallback,
  } from '@/helpers/form'

  const props = defineProps({
    project: { type: Object },
    layout: { type: Object },
  })
  const emit = defineEmits(['saved', 'cancel', 'error'])

  // DEBUG est définie globalement par webpack
  const debug = DEBUG
  // Récupération de la configuration du formulaire
  const configStore = useProjectConfigStore()
  const projectTypeOptions = configStore.getOptions('project_types')
  const invoicingModeOptions = ref(configStore.getOptions('invoicing_modes'))
  const businessTypeOptions = ref(configStore.getOptions('business_types'))
  const formConfigSchema = configStore.getSchema('default')

  // Construction du formulaire
  const formSchema = buildYupSchema(formConfigSchema)
  const initialValues = getDefaults(formSchema)
  // Formulaire vee-validate (se met à jour automatiquement en fonction du schéma)
  const { values, handleSubmit, setFieldValue, isSubmitting } = useForm({
    validationSchema: formSchema,
    initialValues: initialValues,
  })
  // Construction des callbacks submit/cancel
  const projectStore = useProjectStore()
  const onSubmitSuccess = getSubmitModelCallback(emit, projectStore.saveProject)
  const onSubmitError = getSubmitErrorCallback(emit)
  const onSubmit = handleSubmit(onSubmitSuccess, onSubmitError)
  const onCancel = () => emit('cancel')

  // Gère le rafraichissement du formulaire en fonctoin du project_type_id
  function onProjectTypeChange(project_type_id = null) {
    if (project_type_id === null) {
      project_type_id = values.project_type_id
    }
    if (!project_type_id) {
      return
    }

    console.log('Changement du type de dossier')
    const projectType = projectTypeOptions.find(
      (item) => item.id == parseInt(project_type_id)
    )

    if (projectType.name != 'default') {
      setFieldValue('mode', 'ht')
      invoicingModeOptions.value = [{ name: 'ht' }]
    } else {
      invoicingModeOptions.value = configStore.getOptions('invoicing_modes')
    }

    businessTypeOptions.value = configStore
      .getOptions('business_types')
      .filter((item) => projectType.other_business_type_ids.includes(item.id))

    setFieldValue('business_types', [])
  }
  // On le lance une première fois pour filter les options du formulaire en
  // fonction du type de projet par défaut.
  onProjectTypeChange()

  // Raccourci pour le rendu des champs : renvoie les attributs associés à un champ du formulaire
  const getData = (fieldName) => getFieldData(formSchema, fieldName)

  watch(() => values.project_type_id, onProjectTypeChange)

  const Layout = props.layout
</script>
<template>
  <Layout @submitForm="onSubmit" @close="onCancel">
    <template v-slot:title>
      <template v-if="project.id">Modifier un dossier</template>
      <template v-else>Ajouter un dossier</template>
    </template>
    <template v-slot:fields>
      <fieldset class="deformFormFieldset">
        <div class="row form-row">
          <div class="col-md-12">
            <Input v-bind="getData('name')" />
          </div>
        </div>
        <div class="row form-row">
          <div class="col-md-12">
            <RadioChoice
              v-if="projectTypeOptions.length > 1"
              v-bind="getData('project_type_id')"
              :options="projectTypeOptions"
            />
            <Input type="hidden" v-bind="getData('project_type_id')" />
          </div>
        </div>
        <div class="row form-row">
          <div class="col-md-12">
            <RadioChoice
              v-if="invoicingModeOptions.length > 1"
              v-bind="getData('mode')"
              :options="invoicingModeOptions"
              inline
              idKey="value"
            />
            <Input v-bind="getData('mode')" type="hidden" />
          </div>
        </div>
        <div class="row form-row">
          <div class="col-md-12">
            <template v-if="businessTypeOptions.length > 0">
              <CheckboxList
                :options="businessTypeOptions"
                v-bind="getData('business_types')"
                name="business_types"
              />
            </template>

            <Input v-else v-bind="getData('business_types')" type="hidden" />
          </div>
        </div>
      </fieldset>
    </template>
    <template v-slot:buttons>
      <button
        id="deformsubmit"
        name="submit"
        type="submit"
        class="btn btn-primary"
        value="submit"
        :disabled="isSubmitting"
      >
        Valider
      </button>
      <button
        id="deformcancel"
        name="cancel"
        type="button"
        class="btn btn-default"
        @click="onCancel"
      >
        Annuler
      </button>
      <DebugContent v-if="debug" :debug="values" />
    </template>
  </Layout>
</template>
